﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using FileUpload.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly AppDbContext _appDbContext;

        public HomeController(IHostingEnvironment hostingEnvironment, AppDbContext appDbContext)
        {
            _hostingEnvironment = hostingEnvironment;
            _appDbContext = appDbContext;
        }

        public IActionResult New()
        {
            return View();
        }

        [HttpPost]
        public IActionResult New(UserViewModel user)
        {
            if (!ModelState.IsValid)
            {
                return View(user);
            }
            var fileName = Path.Combine("upload", DateTime.Now.ToString("MMddHHmmss") + ".jpg");
            using (var stream = new FileStream(Path.Combine(_hostingEnvironment.WebRootPath, fileName),
                FileMode.CreateNew))
            {
                user.IdCardImg.CopyTo(stream);
            }
            var users = _appDbContext.Set<User>();
            var dbUser = new User()
            {
                Name = user.Name,
                IdCardNum = user.IdNum,
                IdCardImgName = fileName
            };
            users.Add(dbUser);
            _appDbContext.SaveChanges();

            return RedirectToAction(nameof(Index));
        }

        public IActionResult Index()
        {
            var model = _appDbContext.Set<User>()
                .Select(x => new UserViewModel
                {
                    Name = x.Name,
                    IdNum = x.IdCardNum,
                    IdCardImgName = x.IdCardImgName
                }).ToList();
            return View(model);
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}